// 表单验证工具函数

// 验证必填字段
export const required = (value: any): boolean | string => {
  if (value === null || value === undefined || value === '') {
    return '此字段为必填项'
  }
  return true
}

// 验证邮箱格式
export const email = (value: string): boolean | string => {
  const pattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i
  if (!pattern.test(value)) {
    return '请输入有效的邮箱地址'
  }
  return true
}

// 验证最小长度
export const minLength = (min: number) => {
  return (value: string): boolean | string => {
    if (value.length < min) {
      return `最少需要 ${min} 个字符`
    }
    return true
  }
}

// 验证最大长度
export const maxLength = (max: number) => {
  return (value: string): boolean | string => {
    if (value.length > max) {
      return `最多允许 ${max} 个字符`
    }
    return true
  }
}

// 验证数字范围
export const numberRange = (min: number, max: number) => {
  return (value: number): boolean | string => {
    const num = Number(value)
    if (isNaN(num)) {
      return '请输入有效的数字'
    }
    if (num < min || num > max) {
      return `请输入 ${min} 到 ${max} 之间的数字`
    }
    return true
  }
}

// 验证手机号码
export const phoneNumber = (value: string): boolean | string => {
  const pattern = /^1[3-9]\d{9}$/
  if (!pattern.test(value)) {
    return '请输入有效的手机号码'
  }
  return true
}

// 组合多个验证规则
export const compose = (...validators: Array<(value: any) => boolean | string>) => {
  return (value: any): boolean | string => {
    for (const validator of validators) {
      const result = validator(value)
      if (result !== true) {
        return result
      }
    }
    return true
  }
}
